package com.example.dqdq.lzyim_asm_tvapp;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dqdq.lzyim_asm_tvapp.api.API;
import com.example.dqdq.lzyim_asm_tvapp.https.HttpManger;
import com.example.dqdq.lzyim_asm_tvapp.receiver.AdTextReceiver;
import com.example.dqdq.lzyim_asm_tvapp.utils.ActivityCollector;
import com.example.dqdq.lzyim_asm_tvapp.utils.AutoScrollTextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.x;

import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import com.umeng.analytics.MobclickAgent;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

public class VedioActivity extends BaseActivity {

     private WindowManager wm;
     private View vedioView;
     private static WindowManager.LayoutParams params;
     private JCVideoPlayer jcVideoPlayerS;
     private String vedioName="";
     private String vedioUrl="";
     private String loadImg="";


    private ImageButton[] imageViews;
     private View popWindowView;
     private View subtitleView;
    private View imgView;
     private int textrecLen = 60;
    private int imgrecLen = 10;
    private Timer textTimer;
    private String pushid;


    private String path="";
    private String content="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_test);
        try {
            ActivityCollector.addActivity(this);
            ActivityCollector.finishAll(this);
        Intent dataIntent = this.getIntent();
            wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

        String adType=dataIntent.getStringExtra("type");
        JSONObject obj= null;
            obj = new JSONObject(dataIntent.getStringExtra("data"));

        if (adType.equals("img"))
        {
            String[] imgs = obj.getString("content").split(",");//图片URL
            String[] urls=obj.getString("forwardlink").split(",");//点击跳转到的网页
            String[] pusshId=obj.getString("pushid").split(",");//每张图片的ID 用于记录点击量
            pushid=obj.getString("pushid");

            showImg(VedioActivity.this, imgs,urls,pusshId);
        }
        if (adType.equals("vedio"))
        {

            vedioName = dataIntent.getStringExtra("vedioName");
            loadImg = dataIntent.getStringExtra("loadImg");
            vedioUrl = dataIntent.getStringExtra("vedioUrl");
             obj.getString("path");
            ImageLoader.getInstance().init(ImageLoaderConfiguration.
                    createDefault(VedioActivity.this));
             showVedio();
        }

        if (adType.equals("text"))
        {
//            showText(VedioActivity.this, obj.getString("content"));
            show(VedioActivity.this,obj.getString("content"),obj.getString("path"));
            textTimer = new Timer();//定时自动关闭字幕
            textrecLen = 60;
            textTimer.schedule(textTimerTask, 1000, 1000);
            path=obj.getString("path");
            content=obj.getString("content");
        }
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        finish();
//        Intent home = new Intent(Intent.ACTION_MAIN);//为了实现不显示界面的效果  弹出视频后返回桌面
//        home.addCategory(Intent.CATEGORY_HOME);
//        startActivity(home);

    }
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
//        Window window = getWindow();
//        WindowManager.LayoutParams windowParams = window.getAttributes();
//        windowParams.dimAmount = 0.0f;
//
//        window.setAttributes(windowParams);
    }

    /**
     * 显示视频
     */
    private void showVedio() {
        LayoutInflater inflater = LayoutInflater.from(VedioActivity.this);
//        vedioView = inflater.inflate(R.layout.vediolayout, null);

        vedioView=findViewById(R.id.vedioview);
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(VedioActivity.this));
        vedioView.setVisibility(View.VISIBLE);
        ImageButton closeBtn;

        closeBtn = (ImageButton) vedioView.findViewById(R.id.closeBtn);

        jcVideoPlayerS = (JCVideoPlayer) vedioView.findViewById(R.id.vedio);
//        jcVideoPlayerS.setUp("http://2449.vod.myqcloud.com/2449_43b6f696980311e59ed467f22794e792.f20.mp4",
//                "http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640",
//                "一行代码实现视频播放");
        jcVideoPlayerS.setUp(vedioUrl,loadImg,vedioName);
        jcVideoPlayerS.setFocusable(true);

        jcVideoPlayerS.setFocusableInTouchMode(true);

        jcVideoPlayerS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(VedioActivity.this));

                view.setId(R.id.start);
                jcVideoPlayerS.onClick(view);
            }
        });

        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removeVedioView();

            }
        });
        params = new WindowManager.LayoutParams();
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;

//                params.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;

        params.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
        params.width = 800;
        params.height = 700;

        vedioView.requestFocus();
//        wm.addView(vedioView, params);

    }

    private void removeVedioView() {
        if (wm != null) {
              finish();
        }
    }

    /**
     * 定时关闭字幕
     */
    TimerTask textTimerTask = new TimerTask() {
        @Override
        public void run() {
            if (textrecLen != 0) {
                textrecLen--;
            } else if (subtitleView != null) {

                 Message msg=new Message();
                msg.obj=0;
                handler.sendMessage(msg);
                textTimer.cancel();
//                finish();
            }
        }
    };

    TimerTask imgTimerTask = new TimerTask() {
        @Override
        public void run() {
            if (imgrecLen != 0) {
                imgrecLen--;
                Log.e("test", String.valueOf(imgrecLen));

            } else if (imgView != null) {
//                wm.removeView(imgView);
                imgTimerTask.cancel();
                finish();
            }
        }
    };


    /**
     * 显示图片
     * @param context
     * @param imgUrl
     * @param clickUrl
     * @param pusshId
     */
    private void showImg(final Context context, String[] imgUrl, final String[] clickUrl,final String[] pusshId) {
        LayoutInflater inflater = LayoutInflater.from(context);
        imgView = inflater.inflate(getImgView(imgUrl.length), null);

        Button button = (Button) imgView.findViewById(R.id.exitBtn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wm.removeView(imgView);
                finish();

            }
        });

        setImgBtn(context,imgView,imgUrl,clickUrl,pusshId);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        //窗口类型同系统弹出框
        lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        //响应输入法
        //lp.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
        //透明层

//        lp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
//                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        lp.format = PixelFormat.TRANSPARENT;
        lp.width = 1000;
        lp.height = 700;
        lp.gravity = Gravity.CENTER_VERTICAL;
        wm.addView(imgView, lp);
    }

    /**
     * 根据图片数量获取不同的显示界面
     * @param length
     * @return
     */
    private int getImgView(int length)
    {
        int id=0;
        switch (length)
        {
            case 1:
            {
                id=R.layout.ad_img1_layout;
            }
            break;
            case 2:
            {
                id=R.layout.ad_img2_layout;
            }
            break;
            case 3:
            {
                id=R.layout.ad_img3_layout;
            }
            break;
            case 4:
            {
                id=R.layout.ad_img4_layout;
            }
            break;
            case 5:
            {
                id=R.layout.ad_img5_layout;
            }
            break;
            case 6:
            {
                id=R.layout.ad_img6_layout;
            }
            break;
            case 7:
            {
                id=R.layout.ad_img7_layout;
            }
            break;
            case 8:
            {
                id=R.layout.ad_img8_layout;
            }
            break;
            case 9:
            {
                id=R.layout.ad_img9_layout;
            }
            break;
        }

        return id;
    }


    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {

            int type=(int) msg.obj;
            Log.e("test",String.valueOf(type));

            if (type==1)
            {
                Log.e("test","add");

                WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
                //窗口类型同系统弹出框

                lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
                //响应输入法
                //lp.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
                //透明层

                lp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
                lp.format = PixelFormat.TRANSPARENT;
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.MATCH_PARENT;
                lp.gravity = Gravity.CENTER_VERTICAL;

                wm.addView(subtitleView, lp);
            }
            else
            {

                wm.removeView(subtitleView);
                Log.e("test","remove");
                addAdText(3,4,content,path);

                finish();
            }

        }


    };


    /**
     * 根据图片数量设置图片按钮
     * @param context
     * @param view
     * @param imgs
     * @param urls
     * @param pusshId
     */
    private void setImgBtn(final Context context,View view,final String[] imgs,final  String[] urls,final  String[] pusshId)
    {

        Log.e("test", String.valueOf(urls.length));
        Log.e("test", String.valueOf(imgs.length));

        if (imgs.length>0)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img1);
            Glide.with(context).load(API.SERVERC_URL + imgs[0]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    final Uri uri = Uri.parse(urls[0]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                    clickNumber(pusshId[0]);
                    wm.removeView(imgView);
                    finish();


                }
            });
        }

        if (imgs.length>1)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img2);
            Glide.with(context).load(API.SERVERC_URL + imgs[1]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[1]);
                    final Uri uri = Uri.parse(urls[1]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                    wm.removeView(imgView);
                    finish();

                }
            });
        }

        if (imgs.length>2)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img3);
            Glide.with(context).load(API.SERVERC_URL + imgs[2]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[2]);
                    final Uri uri = Uri.parse(urls[2]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                    wm.removeView(imgView);
                    finish();

                }
            });
        }

        if (imgs.length>3)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img4);
            Glide.with(context).load(API.SERVERC_URL + imgs[3]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[3]);
                    final Uri uri = Uri.parse(urls[3]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                    wm.removeView(imgView);
                    finish();

                }
            });
        }
        if (imgs.length>4)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img5);
            Glide.with(context).load(API.SERVERC_URL + imgs[4]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[4]);
                    final Uri uri = Uri.parse(urls[4]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                    wm.removeView(imgView);
                    finish();

                }
            });
        }

        if (imgs.length>5)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img6);
            Glide.with(context).load(API.SERVERC_URL + imgs[5]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[5]);
                    final Uri uri = Uri.parse(urls[5]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                    wm.removeView(imgView);
                    finish();

                }
            });
        }

        if (imgs.length>6)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img7);
            Glide.with(context).load(API.SERVERC_URL + imgs[6]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[6]);
                    final Uri uri = Uri.parse(urls[6]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                    wm.removeView(imgView);
                    finish();

                }
            });
        }

        if (imgs.length>7)
        {
            clickNumber(pusshId[7]);
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img8);
            Glide.with(context).load(API.SERVERC_URL + imgs[7]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Uri uri = Uri.parse(urls[7]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                    wm.removeView(imgView);
                    finish();

                }
            });
        }
        if (imgs.length>8)
        {
            clickNumber(pusshId[8]);
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img9);
            Glide.with(context).load(API.SERVERC_URL + imgs[8]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Uri uri = Uri.parse(urls[8]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(it);
                    wm.removeView(imgView);
                    finish();
                }
            });
        }
    }



    /**
     * 记录点击量
     * @param pushid
     */
    private void clickNumber(String pushid)
    {

        Log.e("Test","id="+pushid);
        if (pushid!=null&&pushid!="")
        {
            Log.e("Test","start");
            x.http().post(HttpManger.getParams(API.TV_CLICK, "id", pushid), new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.e("Test","success");

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    //  Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {
                    //   Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFinished() {

                }
            });
        }
    }

    private void show(Context context, String msg,String imgpath) throws JSONException {
 //        TextView msgTxv;
        LayoutInflater inflater = LayoutInflater.from(VedioActivity.this);

        subtitleView = inflater.inflate(R.layout.bottom, null);
//        msgTxv= (TextView) subtitleView.findViewById(R.id.MsgTxv);
//        msgTxv.setText(array.getJSONObject(0).getString("news"));
//        Download
        //  popView.setOnTouchListener(this);
        TextView editText1 = (TextView) subtitleView.findViewById(R.id.sptxm);
        editText1.setText(msg);

        if (!imgpath.equals(""))
        new DownloadImageTask().execute(API.SERVERC_URL+imgpath);
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Drawable>
    {

        protected Drawable doInBackground(String... urls) {
            return loadImageFromNetwork(urls[0]);
        }

        protected void onPostExecute(Drawable result) {
//                mImageView.setImageDrawable(result);

            if (result!=null)
            {
            TextView editText1 = (TextView) subtitleView.findViewById(R.id.sptxm);
            result.setBounds(0, 0, result.getIntrinsicWidth() / 4, result.getIntrinsicHeight() / 4);
            editText1.setCompoundDrawables(result, null, null, null);
            Message msg=new Message();
                msg.obj=1;
                handler.sendMessage(msg);
                Log.e("test","send");
            }

        }
    }

    private Drawable loadImageFromNetwork(String imageUrl)
    {
        Drawable drawable = null;
        try {
            // 可以在这里通过文件名来判断，是否本地有此图片
            drawable = Drawable.createFromStream(
                    new URL(imageUrl).openStream(), "image.jpg");
        } catch (IOException e) {
            Log.d("test", e.getMessage());
        }
        if (drawable == null) {
            Log.d("test", "null drawable");
        } else {
            Log.d("test", "not null drawable");
        }

        return drawable ;
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    public void addAdText(int number, int time,String content,String imgpath)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        cal.add(Calendar.SECOND, (int) time);
         Activity activity = this;
        Intent intent = new Intent(activity, AdTextReceiver.class);
        intent.setClass(activity, AdTextReceiver.class);
         intent.putExtra("msg", "play_hskay");
        intent.putExtra("number", number);
        intent.putExtra("content", content);
        intent.putExtra("imgpath", imgpath);

        PendingIntent pi = PendingIntent.getBroadcast(activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager am = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
    }
}
